package cn.tedu.coolsharkmall.ex.handler;

import cn.tedu.coolsharkmall.ex.ServiceException;
import cn.tedu.coolsharkmall.web.JsonResult;
import cn.tedu.coolsharkmall.web.ServiceCode;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;


@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler
    public JsonResult<Void> handleException(ServiceException e) {
        return JsonResult.fail(e);
    }

    @ExceptionHandler()
    public JsonResult<Void> handleBindException(BindException e){
        String message = e.getFieldError().getDefaultMessage();
//        List<FieldError> fieldErrors = e.getFieldErrors();
//        for (FieldError fieldError: fieldErrors) {
//            message += fieldError.getDefaultMessage()
//        }
        return JsonResult.fail(ServiceCode.ERROR_BAD_REQUEST, message);
    }

    @ExceptionHandler
    public JsonResult<Void> handleConstraintViolationException(ConstraintViolationException e){
        String message = e.getMessage();
        return JsonResult.fail(ServiceCode.ERROR_CONSTRAINT, message);
    }

    @ExceptionHandler
    public JsonResult<Void> handleThrowable(Throwable e){
        String message = "(开发过程中，如果看到此信息，补充exception方法)";
        e.printStackTrace(); //再生产环境中，禁止使用此语句!
        return JsonResult.fail(ServiceCode.NON_KNOWN, "服务器忙，请稍后再次尝试");
    }


}
